/**
 * 订单详情页
 * @author zhangqiang
 * @date   2017/3/11
 */

import React, {Component} from 'react'
import {connect} from 'react-redux'
import {orderDetails_view, evaluationDetails, setEvaluationDetails} from '../../actions/orderDetails';
import {handlingList} from '../../actions/handlingAction';
import Login from '../../utils/loginOperation_bak'
import AlipayJSOperation from '../../utils/alipayJSOperation';
import PageBar from '../../components/common/pageBar';
import typeOfBrowser from '../../utils/typeOfBrowser';
import {Button, Toast} from 'antd-mobile';
/*import HandleProcess from '../../components/OrderDetails/handelProcess/handleProcess';*/
import {getWeixinConfig} from '../../actions/homeAction';
import Style from './index.scss';
import BackMeanSure from '../../utils/backMeanSure';
import common from '../../utils/common';
import urlOperation from '../../utils/urlOperation';
import ItemWithRightArrow from '../../components/common/itemWithRightArrow';
import CustomerService from '../../components/common/customerService';
import ServiceEvaluationDetails from '../../components/ServiceEvaluationDetails';
import ReModal from '../../components/common/reModal'

//加载依赖
import jsApi from '../../utils/cx580.jsApi'
import SendCxytjMessage from '../../utils/sendCxytjMessage';
import appVersion from "../../utils/appVersion";


class OrderDetails extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [], //详情数据
            statusLength: '', //订单的流程 *数字
            serviceEvaluation: {
                default: '',
                getData: (starNum, details) => this.getValuationData(starNum, details), // 子组件：send
            },// 服务评价弹窗情况
        };
        this.getUrlParam = this.getUrlParam.bind(this);
        this.detailFlow = this.detailFlow.bind(this);
        this.detailHandling = this.detailHandling.bind(this);
        this.confirmStatus = this.confirmStatus.bind(this);
        this.setJump = this.setJump.bind(this);
        // this.backMeanSureInstance = new BackMeanSure(this.goHome.bind(this), 'orderDetails');
    }


    //返回首页
    goHome() {
        history.pushState({}, '', '');
        let backNumber = -1 * history.length + 1;
        history.go(backNumber);
        /* let userChannel = typeOfBrowser.getChannelOfBrowser();
         if (urlOperation.getParameters()['type'] == 'orderList') {
             history.pushState({}, '', '');
             let backNumber = -1 * history.length + 1;
             history.go(backNumber);
         }
         else {
             switch (userChannel) {
                 case 'aliPay':
                     AlipayJSOperation.closeView();
                     break;
                 case 'app':
                     common.closeAppView();
                     break;
                 case 'weixin':
                     wx.closeWindow();
                     break;
                 case 'qq':
                     mqq.ui.popBack();
                     break;
             }
         }*/
    }

    //发送初始化埋点数据
    sendInitMessage(inspectionType) {
        let eventId = inspectionType == 1 ? 'H5_P_Interspection_EnterOlineOrderDetails' : 'H5_P_Interspection_EnterOrderDetails';
        SendCxytjMessage.sendMessage({eventId: eventId});
    }


    componentWillMount() {
        //如果没有登陆，登陆拿到user
        Login.appLogin(() => {
            //详情
            this.props.dispatch(orderDetails_view({
                orderId: this.getUrlParam('OutTradeNo'),
            }, (data) => {
                this.setState({
                    data: data,
                });
                //    console.log("orderDetails_view = "+JSON.stringify(data));
                this.sendInitMessage(data.inspectionType);
            }));

            // 进度条长度
            this.props.dispatch(handlingList({
                orderId: this.getUrlParam('OutTradeNo'),
            }, (res) => {
                this.setState({
                    statusLength: res.length,
                })
            }))
        });


        let userChannel = typeOfBrowser.getChannelOfBrowser();

        switch (userChannel) {
            case 'aliPay':
                userChannel = 'alipay';
                break;
            case 'app':
                userChannel = 'app';
                break;
            case 'weixin':
                userChannel = 'weixin';
                break;
            case 'qq':
                userChannel = 'qq';
                break;
        }

        if (userChannel == 'app') {
            localStorage.removeItem('type')
        }

        /* if (this.getUrlParam('type') == 'orderList') {    //如果是我的订单入口进入
         if (userChannel!='app') {
         var href = window.location.href.replace(window.location.hash, '');
         sessionStorage.setItem('loginStatus', 'false');
         window.location.replace(`${href}?orderId=`+this.getUrlParam('OutTradeNo')+'&detailUserType='+userChannel);
         localStorage.setItem('type', 'orderList');
         }
         } else {
         localStorage.removeItem('type')
         }*/

    }

    componentDidMount() {
        // window.addEventListener("unload",function(e){
        //   //alert('离开');
        // },false);
        localStorage.removeItem('addressList_action')

        // this.backMeanSureInstance.bindBackMeansure();
        document.querySelector("title").innerHTML = "订单详情";
        // 在支付宝兼容性
        AlipayJSOperation.setTransparentTitle('none');
        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false);
        //设置标题
        AlipayJSOperation.setTitle('订单详情');
        //设置标题颜色
       // AlipayJSOperation.setBarColor('#2FB3FE');
        //  AlipayJSOperation.setLeftButtonStatus(this.setJump);
        //屏蔽微信分享
        this.WeXinOperation();
    }

    WeiXinConfig(config) {
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: config.appId, // 必填，公众号的唯一标识
            timestamp: config.timestamp, // 必填，生成签名的时间戳
            nonceStr: config.nonceStr, // 必填，生成签名的随机串
            signature: config.signature,// 必填，签名，见附录1
            jsApiList: ['hideOptionMenu', 'closeWindow'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(() => {
            wx.hideOptionMenu();
        });
    }

    //微信屏蔽分享功能
    WeXinOperation() {
        if (typeOfBrowser.getChannelOfBrowser() == 'weixin') {
            this.props.dispatch(getWeixinConfig({signUrl: location.href}, (result) => {
                this.WeiXinConfig(result);
                //切换页面时再次触发微信配置
                window.addEventListener('hashchange', (e) => {
                    this.WeiXinConfig(result);
                }, false);
            }))
        }
    }


    componentDidUpdate() {

    }

    componentWillUnmount() {
        AlipayJSOperation.removeLeftButtonEvent();
    }

    setJump() {
        if (location.href.indexOf('orderDetails') > -1) {  //如果是详情页关闭 页面进支付宝首页
            AlipayJSOperation.closeView()
        }
        //if ( localStorage.getItem('detailUserType') == 'alipay_city'||localStorage.getItem('detailUserType') == 'alipay') {    ///如果是城市服务和公众号就关闭localStorage.getItem('detailUserType') == 'alipay'
        //if(sessionStorage.getItem('pop_s')){
        // if (location.href.indexOf('orderDetails') > -1) {  //如果是详情页关闭 页面进支付宝首页
        // var prod = window.location.href.indexOf('https://annualcheck.cx580.com/') > -1 ? true : false; //是否为生产环境
        //  if(prod){
        //     window.location.replace('https://banli.cx580.com/myorder/orderList.aspx?userType=alipay');
        //  }else {
        //     window.location.replace('http://webtest.cx580.com:5555/myorder/orderList.aspx?userType=alipay');
        //  }
        // // window.location.replace(`${href}#/orderDetails/?OutTradeNo=${orderId}`);
        //   // let gotoNum = parseInt('-'+window.history.length.toString())+1;
        //   // window.history.go(gotoNum);
        // }
        // }else {
        //   if (location.href.indexOf('orderDetails') > -1) {  //如果是详情页关闭 页面进支付宝首页
        //     AlipayJSOperation.closeView()
        //   }
        //}
        // }
    }

    // 取得某个url参数
    getUrlParam(name, url) {
        /*    return urlOperation.getParameters()[name];*/
        var urlSearch = '?' + window.location.href.split('?')[1].split('/#/')[0];
        var search = url || urlSearch.substr(1);

        if (search != '') {
            var re = new RegExp('(^|&|\\?)' + name + '=([^&]*)($|&)');
            var arr = search.match(re);
            if (arr !== null) {
                return decodeURI(arr[2]);
            }
        }
        return '';
    }

    sendMessage(type) {
        window.cxytj.recordUserBehavior({
            eventId: type,
            eventType: '2', //事件类型
            eventTime: '',  //触发时间
        });
    }

    //发送继续办理埋点信息
    sendContinueMessage() {
        let eventId = this.state.data.inspectionType == 1 ? 'H5_E_OlineOrderDetails_ClickContinuetohandle' : 'H5_E_OrderDetails_ClickContinuetohandle';
        SendCxytjMessage.sendMessage({eventId: eventId});
    }

    // 流程按钮
    detailFlow() {
        //跳转

        localStorage.setItem('type', 'orderList');
        // 如果是完结，特殊弹窗
        if (this.state.data.orderStatus == 8 || this.state.data.orderStatus == 9) {
            // 已经完结添加评价功能
            // 这里假装有数据，假装不用请求：serviceEvaluation
            if (this.state.serviceEvaluation.default.points > 1) {
                ReModal.showComponent(<ServiceEvaluationDetails {...this.state.serviceEvaluation} />);
                //发送埋点
                SendCxytjMessage.sendMessage({eventId:  this.state.data.inspectionType == 1 ? 'H5_E_OlineOrderDetails_ClickCheckEvaluation' : 'H5_E_OrderDetails_ClickCheckEvaluation'});

            } else {
                this.props.dispatch(evaluationDetails({
                    orderId: this.getUrlParam('OutTradeNo'),
                }, (res) => {
                    this.setState({
                        serviceEvaluation: Object.assign(this.state.serviceEvaluation, { //''年检计算机的props数据
                            default: res,
                        })
                    });
                    ReModal.showComponent(<ServiceEvaluationDetails {...this.state.serviceEvaluation} />);

                }));
                //发送埋点
                SendCxytjMessage.sendMessage({eventId:  this.state.data.inspectionType == 1 ? 'H5_E_OlineOrderDetails_ClickEvaluate' : 'H5_E_OrderDetails_ClickEvaluate'});
            }

        } else {
            // 其他状态跳转
            if (this.state.data.confirmStatus == 0 || this.state.data.confirmStatus == -1 || this.state.data.confirmStatus == -2) {
                this.sendContinueMessage();
                //this.context.router.push('annualInspection' + '/' + (this.getUrlParam('OutTradeNo')));
                //此处是app的兼容性措施，6.3版本之后将兼容去掉，app已解决此问题（api_version为新sdk标识，6.3以上会有api_version）
                    if(typeOfBrowser.getChannelOfBrowser()=='app') {
                        if (appVersion.getMainVersionByCount()<6.33) {
                            let urlOfNow = window.location.href;
                            let APPbaseApiUrl = urlOfNow.replace(window.location.hash, '').split('?')[0].replace('#/', '');
                            let urls = this.getUrlParam('OutTradeNo');
                            jsApi.call({
                                "commandId": "",
                                "command": "close",
                                "data": {}
                            }, function () {
                            });

                            jsApi.call({
                                'commandId': '',
                                'command': 'openNewBrowserWithURL',
                                'data': {
                                    'url': `${APPbaseApiUrl}#/annualInspection/${urls}`,
                                    'umengId': 'cfw_youkachongzhi',
                                    'showTitleLayout': 'false' //是否显示到导航栏
                                }
                            }, function (data) {
                            });
                        }
                        //新版本app直接跳转，无需兼容
                        else {
                            this.context.router.push('annualInspection' + '/' + (this.getUrlParam('OutTradeNo')));
                        }
                    }
                    else{
                        this.context.router.push('annualInspection' + '/' + (this.getUrlParam('OutTradeNo')));
                    }

            } else if (this.state.data.confirmStatus == 1) {
                //上线检直接跳上线检结果页
                this.context.router.push((this.state.data.inspectionType == 2 ? 'sendTheAddress/overLine' : 'mailingAddress') + '/' + (this.getUrlParam('OutTradeNo')));

                if (this.state.data.inspectionType == 1) {
                    //免检跳转至填写回寄地址
                    SendCxytjMessage.sendMessage({eventId: 'H5_E_OlineOrderDetails_ClickEditAddress'});
                }
            } else if (this.state.data.confirmStatus == 2 || this.state.data.confirmStatus == 3) {
                if (this.state.data.inspectionType == 2) {
                    //上线检直接跳上线检结果页
                    this.context.router.push('sendTheAddress/overLine/' + (this.getUrlParam('OutTradeNo')));
                    SendCxytjMessage.sendMessage({eventId: 'H5_E_OrderDetails_CheckSendDetails'});
                }
                else {
                    SendCxytjMessage.sendMessage({eventId: this.state.data.confirmStatus == 2 ? 'H5_E_OlineOrderDetails_ClickComfirmSend' : 'H5_E_OlineOrderDetails_CheckSendDetails'});
                    if (this.state.data.mailType == 'ems') { //邮政
                        this.context.router.push('sendTheAddress/' + 'ems/' + 'btnNo' + '/' + (this.getUrlParam('OutTradeNo')));
                    } else if (this.state.data.mailType == 'person') { //自主
                        this.context.router.push('sendTheAddress/' + 'person/' + 'btnNo' + '/' + (this.getUrlParam('OutTradeNo')));
                    }
                }
            }
        }
        //0：未确认项目；1：已确认项目，但未确认提交；2：确认提交 annualDataMailDoor
    }

    //返回（ServiceEvaluationDetails组件返回的数据） 里面评价的情况:多少星星和评语
    getValuationData(starNum, details) {
        if (!starNum) {
            return Toast.info('请选择服务评价', 1);
        }

        this.props.dispatch(setEvaluationDetails({
            orderId: this.getUrlParam('OutTradeNo'),
            points: starNum,
            comments: details,
        }, (res) => {
            if (res.data.resultFlag) {
                this.setState({
                    serviceEvaluation: Object.assign(this.state.serviceEvaluation, { //''年检计算机的props数据
                        default: res,
                    }),
                    data: Object.assign(this.state.data, { //
                        msg: '查看评价',
                    })
                });
                ReModal.close();
            } else {
                Toast.info(res.msg, 1);
            }

        }))
    }

    //发送查看订单进度详情
    sendProgressMessage() {
        let eventId = this.state.data.inspectionType == 1 ? 'Insepection_ViewExemptionOrderProgress' : 'Insepection_ViewOnlineOrderProgress';
        SendCxytjMessage.sendMessage({eventId: eventId});
    }

    detailHandling(url) { //办理流程
        if (this.state.data.orderStatus == 4) {
            this.context.router.push(url + '/' + (this.getUrlParam('OutTradeNo') + '/' + this.state.data.orderTitle + '/' + 'no'));
        } else {
            this.context.router.push(url + '/' + (this.getUrlParam('OutTradeNo') + '/' + this.state.data.orderTitle + '/' + 'yes'));
        }
        this.sendProgressMessage();
    }

    getHeaderContentClass() {
        return this.state.data.orderStatus == 4 ? Style.headerContent + ' ' + Style.unableHeaderContent : Style.headerContent;
    }

    confirmStatus() {
        //按钮文字修改为从后端获取
        return this.state.data.msg;
        /* if (this.state.data.confirmStatus == 0 || this.state.data.confirmStatus == 1) {
             return '继续办理年检手续';
         } else if (this.state.data.confirmStatus == 2) {
             return '前往寄送资料';
             /!*  if (this.state.data.mailType == 'ems') {
              return '查看年检资料及收件地址'
              } else if (this.state.data.mailType == 'person') {
              return '查看我的收件地址'
              }
              *!/
         } else if(this.state.data.confirmStatus==3){
             return '查看寄送信息';
         }*/
    }

    /* structProcess() {
     let allLength = this.state.data.mailType == 'ems' ? 6 : 5;
     let current = this.state.statusLength - 1;
     let error = false;
     if (this.state.data.orderStatus == 4) {
     current = 2;
     error = true;
     }
     return <HandleProcess all={allLength} current={current} error={error}/>
     }*/

    //根据不同的车检或者寄递状态显示图标
    rendermailAndDriveTypeItemImg() {
        if (this.state.data.inspectionType == undefined) {
            return '';
        }
        return this.state.data.inspectionType == '1' ?
            <img src={this.state.data.mailType == 'ems' ? './images/icon_youzheng.png' : './images/icon_jisong.png'}/> :
            <img src={this.state.data.driveType == '1' ? './images/icon_daijia.png' : './images/icon_zijia.png'}/>
    }

    //根据不同的车检或者寄递状态显示图标后面的文字
    rendermailAndDriveTypeItemText() {
        if (this.state.data.inspectionType == undefined) {
            return '';
        }
        return <div>{this.state.data.inspectionType == '1' ? this.state.data.mailType == 'ems' ? '邮政上门' : '自主寄送' : this.state.data.driveType == '1' ? '代驾检测' : '自驾检测'}</div>;
    }

    //过线检办理地区
    renderHandleAddress(){
        return this.state.data.inspectionType == '2'?<div>
            <div>车辆所在地：</div>
            <div>{this.state.data.regionName}</div>
        </div>:'';
    }


    render() {
        let dataText = this.state.data,
            Progress,  //邮政6步
            Progress_b;  //自主5步

        if (this.state.statusLength == 1) {
            Progress = Style.success_a;
            Progress_b = Style.success_b_a;
        } else if (this.state.statusLength == 2) {
            Progress = Style.success_b;
            Progress_b = Style.success_b_b;
        } else if (this.state.statusLength == 3) {
            Progress = Style.success_c;
            Progress_b = Style.success_b_c;
        } else if (this.state.statusLength == 4) {
            Progress = Style.success_d;
            Progress_b = Style.success_b_d;
        } else if (this.state.statusLength == 5) {
            Progress = Style.success_e;
            Progress_b = Style.success_b_e;
        } else if (this.state.statusLength == 6) {
            Progress = Style.success_f;
        }

        return (
            <div className={Style.noOrderDetails}>
                <PageBar title="订单详情"/>
                {/*<div style = {{height:'24px'}}></div>*/}
                <div className={this.getHeaderContentClass()}>
                    <div className={Style.headerMessage} onClick={() => this.detailHandling('handlingProgress')}>
                        <ItemWithRightArrow className={Style.arrowItem}>
                            <div
                                className={Style.alreadyPaid + ' ' + (dataText.orderStatus == 4 ? Style.red : '')}>{dataText.handleMsg}</div>
                        </ItemWithRightArrow>
                        <p>
                            {dataText.handleRemark}
                        </p>
                    </div>
                    {
                        dataText.orderStatus == 4 ? '' :
                            <Button
                                className={dataText.orderStatus == 8 ? Style.btn_inspection_white : Style.btn_inspection}
                                type="ghost" size={'default'}
                                onClick={e => this.detailFlow()}>
                                {this.confirmStatus()}
                            </Button>
                    }
                </div>

                <div className={Style.detailContent}>
                    <ul className={Style.technological}>
                        <li><span>{dataText.orderTitle}</span></li>
                        {
                            dataText.descList ?
                                dataText && dataText.descList.map((e, i) => {
                                    return <li key={i}>{e.desc}</li>
                                }) : null
                        }
                    </ul>
                    <div className={Style.mailAndDriveTypeItem}>
                        <div>
                            <div>{this.state.data.inspectionType == '1' ? '年检资料寄送方式：' : '上线检车检方式：'}</div>
                            {this.rendermailAndDriveTypeItemImg()}
                            {this.rendermailAndDriveTypeItemText()}
                        </div>
                        {/*过线检显示办理地区*/}
                        {this.renderHandleAddress()}
                    </div>
                    <div className={Style.cost}>
                        <ul>
                            <li>
                                <span>订单总费用：</span>
                                <span>{'￥'}<span>{dataText.orderAmount}</span></span>
                            </li>
                            {
                                dataText.vipDiscountAmount == 0 ? '' :
                                    <li>
                                        <span>会员减免：</span>
                                        <span>{'￥'}<span>{dataText.vipDiscountAmount}</span></span>
                                    </li>
                            }
                            {
                                dataText.couponDiscountAmount == 0 ? '' :
                                    <li>
                                        <span>优惠劵减免：</span>
                                        <span>{'￥'}<span>{dataText.couponDiscountAmount}</span></span>
                                    </li>
                            }
                            {
                                dataText.activity && dataText.activity.title.length > 0 ?
                                    <li>
                                        <span>{dataText.activity.title}：</span>
                                        <span>{'￥'}<span>{dataText.activity.account}</span></span>
                                    </li> : ''

                            }
                            <li>
                                <span>总计：</span>
                                <span>{'￥'}<span>{dataText.payAmount}</span></span>
                            </li>
                        </ul>
                        <ul>
                            <li>
                                <span>实际支付：</span>
                                <span>{'￥'}<span>{dataText.payAmount}</span></span>
                            </li>
                        </ul>
                        <div className={Style.OrderDetails}>
                            <p>订单编号：<span>{dataText.orderId}</span></p>
                            <p>支付方式：<span>{
                                dataText.payType
                            }</span></p>
                            <p>支付交易号：<span>{dataText.payNo}</span></p>
                            <p>创建时间：<span>{dataText.createTime}</span></p>
                            <p>支付时间：<span>{dataText.payTime}</span></p>
                            {
                                dataText.orderStatus == 4 ? <p>订单关闭时间：<span>{dataText.refundTime}</span></p> : ''
                            }
                        </div>
                    </div>
                </div>
                <CustomerService rightText="联系客服"/>
            </div>
        )
    }
}

OrderDetails.defaultProps = {
    autonomy: [0, 1, 2, 3, 4], //自主 5
    post: [0, 1, 2, 3, 4, 5,] //邮政6步
}

//react router跳转时使用了context，此处需要显式声明
OrderDetails.contextTypes = {
    router: React.PropTypes.object.isRequired
};

export default connect()(OrderDetails)
